package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.RoleEnum;
import com.example.springboot.entity.User;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import com.example.springboot.service.IRepairService;
import com.example.springboot.entity.Repair;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-08-31
 */
@RestController
@RequestMapping("/repair")
public class RepairController {

    @Resource
    private IRepairService repairService;

    //新增或者更新
    @PostMapping
    public Result save(@RequestBody Repair repair) {  //@RequestBody接收前端数据
        if (repair.getId() == null) {
            // 获取当天时间
            repair.setTime(DateUtil.today());
            repair.setUser(TokenUtils.getCurrentUser().getUsername());
        }
        repairService.saveOrUpdate(repair);
        return Result.success();
    }

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(repairService.list());
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(repairService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(repairService.removeByIds(ids));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(repairService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {

        QueryWrapper<Repair> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        User currentUser = TokenUtils.getCurrentUser();
        // 角色是普通用户
        if(RoleEnum.ROLE_USER.toString().equals(currentUser.getRole())){
           // 只有自己的报修单或者是审核通过的报修单才可以看
            queryWrapper.eq("user",currentUser.getUsername()).or().eq("state","审核通过");
        }
        return Result.success(repairService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}



